package com.yaodian100.ec.mailbanner.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.yaodian100.core.common.dao.ObjectDao;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.impl.DomainServiceImpl;
import com.yaodian100.ec.mailbanner.entity.MailBanner;
import com.yaodian100.ec.mailbanner.entity.MailBannerCoupon;
import com.yaodian100.ec.mailbanner.service.MailBannerService;

/**
 * @author matt.tsai
 *
 */
public class MailBannerServiceImpl extends DomainServiceImpl<MailBanner> implements	MailBannerService {
	private ObjectDao<MailBannerCoupon> mailBannerCouponDao;
	
	@Autowired
	private PlatformTransactionManager transactionManager;
	
	/* (non-Javadoc)
	 * @see com.yaodian100.ec.mailbanner.service.MailBannerService#importMailBannerCoupon(java.io.File)
	 */
	@Override
	public void importMailBannerCoupon(long mailBannerId,File couponTxtFile) throws CoreException {
		BufferedReader in = null;
		int index = 0;
		try {
			in = new BufferedReader(new FileReader(couponTxtFile));
			String data;
			DefaultTransactionDefinition df = new DefaultTransactionDefinition();
			df.setReadOnly(false);
			df.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
			while ((data=in.readLine()) != null) {
				index++;
				if (index == 1 || data.trim().length()==0) continue; //第一行表頭及空白行 忽略
				TransactionStatus ts = null;
				try {
					ts = this.transactionManager.getTransaction(df);
					MailBannerCoupon coupon = new MailBannerCoupon();
					String[] couponData = data.split(",");
					coupon.setMailBannerId(mailBannerId);
					coupon.setCouponCode(couponData[1].trim());
					this.mailBannerCouponDao.save(coupon);
					transactionManager.commit(ts);
				} catch (Exception e) {
					try {
						transactionManager.rollback(ts);
					} catch (Exception e1) {}
					e.printStackTrace();
					throw new CoreException("MailBannerService:第"+index+"行资料无法汇入");
				}
			}	
		} catch (Exception e) {
			e.printStackTrace();
			throw new CoreException("MailBannerService:"+e.getMessage(),e);
		} finally {
			try {
				in.close();
			} catch (Exception e) {}
		}
	}
	
	
	/* (non-Javadoc)
	 * @see com.yaodian100.ec.mailbanner.service.MailBannerService#getMailBannerByPosition(java.lang.String)
	 */
	@Override
	public List<MailBanner> getMailBannerByPosition(String position)
			throws CoreException {
//		StringBuffer sql = new StringBuffer();
//		sql.append("SELECT * FROM EC_MAIL_BANNER_MAIN WHERE TO_CHAR(SYSDATE,'YYYY/MM/DD HH24:MM') BETWEEN TO_CHAR(START_DATE,'YYYY/MM/DD HH24:MM') AND TO_CHAR(END_DATE,'YYYY/MM/DD HH24:MM') ");
//		sql.append(" AND POSITION LIKE '%'||?||'%'");
//		sql.append(" ORDER BY MODIFY_DATE DESC,CREATE_DATE DESC");
//		
//		List<Object> attrs = new ArrayList<Object>();
//		attrs.add(position);
//		
//		List<MailBanner> list = super.getDao().getSQLQueryByList(sql.toString(), attrs, 0, -1);
//		System.out.println("----------"+list.size());
		
		Map<String,Serializable> attrs = new HashMap<String,Serializable>();
		attrs.put("position", position);
		List<MailBanner> list = super.getDao().getNameQuery("MailBanner.getMailBannerByPosition", attrs, 0, -1);
		for (MailBanner mailBanner:list) {
			if (mailBanner.getCouponLink().intValue() == 1) {
				String couponCode = this.getFreeCoupon(mailBanner.getId());
				mailBanner.setFreeCouponCode(couponCode);
			}
		}
		return list;
	}

	public String getFreeCoupon(long mailBannerId) throws CoreException {
		Map<String, Serializable> attrs = new HashMap<String, Serializable>();
		attrs.put("mailBannerId", mailBannerId);
		List<MailBannerCoupon> list = this.mailBannerCouponDao.getNameQuery("MailBannerCoupon.getFreeCoupon", attrs, 0, 1);
		if (list.size() == 0) {
			return null;
		} 
		MailBannerCoupon coupon = list.get(0);
		coupon.setPublishDate(new Date());
		this.mailBannerCouponDao.save(coupon);
		
		return coupon.getCouponCode();
	}


	public ObjectDao<MailBannerCoupon> getMailBannerCouponDao() {
		return mailBannerCouponDao;
	}


	public void setMailBannerCouponDao(
			ObjectDao<MailBannerCoupon> mailBannerCouponDao) {
		this.mailBannerCouponDao = mailBannerCouponDao;
	}


	public PlatformTransactionManager getTransactionManager() {
		return transactionManager;
	}


	public void setTransactionManager(PlatformTransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}

}
